﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;

namespace Common
{
    public class NetworkCommon
    {
        /// <summary>
        /// Get local ip, using for winform and webform
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            string ip = null;

            // Resolves a host name or IP address to an IPHostEntry instance.
            // IPHostEntry - Provides a container class for Internet host address information. 
            System.Net.IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

            // IPAddress class contains the address of a computer on an IP network. 
            foreach (System.Net.IPAddress ipAddress in ipHostEntry.AddressList)
            {
                // InterNetwork indicates that an IP version 4 address is expected 
                // when a Socket connects to an endpoint
                if (ipAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    ip = ipAddress.ToString();
                }
            }
            return ip;
        }

        public static bool SentMail(string ToEmail, string Body, string Title, string Smtp, string FromEmail, string Password, string EmailName)
        {
            try
            {
                var mail = new SmtpClient(Smtp);//google thêm port 587
                //mail.EnableSsl = true;
                var mailC = new MailMessage(FromEmail, ToEmail, Title, Body) { From = new MailAddress(FromEmail, EmailName), IsBodyHtml = true };
                mail.DeliveryMethod = SmtpDeliveryMethod.Network;
                //username,pass
                mail.Credentials = new System.Net.NetworkCredential(FromEmail, Password);
                mail.Send(mailC);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// Ham gui Get Request
        /// </summary>
        /// <param name="requestUrl">Dia chi can goi</param>
        /// <param name="cookieCon"></param>
        /// <param name="referer">Dia chi lien quan, duoc goi truoc do</param>
        /// <param name="htmlResult">Ket qua Html tra ve</param>
        /// <param name="nextLocation">Dia chi tiep theo</param>
        /// <param name="allowRedirect">Co cho tu dong chuyen trang khong</param>
        /// <returns></returns>
        public static bool SendGetRequest(string requestUrl, CookieContainer cookieCon, string referer, out string htmlResult
            , out string nextLocation, bool allowRedirect)
        {
            bool loadSuccess = false;
            nextLocation = string.Empty;
            string resultOutput = string.Empty;

            try
            {
                var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

                webRequest.AllowAutoRedirect = false;
                webRequest.Timeout = 100000; // 100 secs
                webRequest.AutomaticDecompression = DecompressionMethods.GZip;
                webRequest.CookieContainer = cookieCon;

                webRequest.UserAgent = "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7";
                webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                webRequest.Headers[HttpRequestHeader.AcceptLanguage] = "en-us,en;q=0.5";
                webRequest.Headers[HttpRequestHeader.AcceptEncoding] = "gzip,deflate";
                webRequest.Headers[HttpRequestHeader.AcceptCharset] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";
                webRequest.KeepAlive = false; //Fix "The server committed a protocol violation. Section=ResponseStatusLine"
                if (!string.IsNullOrEmpty(referer.Trim()))
                    webRequest.Referer = referer;
                webRequest.ContentType = "application/x-www-form-urlencoded";

                webRequest.Method = "GET";
                using (var response = (HttpWebResponse)webRequest.GetResponse())
                {
                    cookieCon.Add(webRequest.RequestUri, response.Cookies);
                    nextLocation = response.GetResponseHeader("Location");
                    using (var buffer = new BufferedStream(response.GetResponseStream()))
                    {
                        using (var readStream = new StreamReader(buffer, Encoding.UTF8))
                        {
                            resultOutput = readStream.ReadToEnd();
                        }
                    }
                }
                loadSuccess = true;
            }
            catch (ThreadAbortException ex)
            {
            }
            catch (WebException ex)
            {
            }
            finally
            {
                htmlResult = resultOutput;
            }
            return loadSuccess;
        }

        /// <summary>
        /// Ham gui Post request
        /// </summary>
        /// <param name="requestUrl">Dia chi can goi</param>
        /// <param name="cookieCon"></param>
        /// <param name="postData"></param>
        /// <param name="referer">Dia chi lien quan, duoc goi truoc do</param>
        /// <param name="htmlResult">Ket qua Html tra ve</param>
        /// <param name="nextLocation">Dia chi tiep theo</param>
        /// <param name="allowRedirect">Co cho tu dong chuyen trang khong</param>
        /// <returns></returns>
        public static bool SendPostRequest(string requestUrl, CookieContainer cookieCon, string postData, string referer
            , out string htmlResult, out string nextLocation, bool allowRedirect)
        {
            bool loadSuccess = false;
            nextLocation = string.Empty;
            string resultOutput = string.Empty;
            try
            {
                byte[] dataByte = new ASCIIEncoding().GetBytes(postData);
                var webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
                webRequest.Timeout = 100000; // 100 secs
                webRequest.Method = "POST";
                webRequest.KeepAlive = true;
                webRequest.AllowAutoRedirect = allowRedirect;
                webRequest.Headers.Add("Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                webRequest.Headers.Add("Keep-Alive:15");
                webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                if (!string.IsNullOrEmpty(referer.Trim()))
                {
                    webRequest.Referer = referer;
                }
                webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0";
                webRequest.ContentLength = postData.Length;
                webRequest.Proxy = null;
                webRequest.CookieContainer = cookieCon;
                Stream postStream = webRequest.GetRequestStream();
                postStream.Write(dataByte, 0, dataByte.Length);
                postStream.Flush();
                postStream.Close();
                using (var response = (HttpWebResponse)webRequest.GetResponse())
                {
                    cookieCon.Add(webRequest.RequestUri, response.Cookies);
                    nextLocation = response.GetResponseHeader("Location");
                    using (var buffer = new BufferedStream(response.GetResponseStream()))
                    {
                        using (var readStream = new StreamReader(buffer, Encoding.UTF8))
                        {
                            resultOutput = readStream.ReadToEnd();
                        }
                    }
                }
                loadSuccess = true;
            }
            catch (ThreadAbortException ex)
            {
            }
            catch (WebException ex)
            {
            }
            finally
            {
                htmlResult = resultOutput;
            }
            return loadSuccess;
        }

    }
}
